<?php

namespace app\web\controller;

use app\BaseController;
use app\common\model\OfficialAccountModel;
use EasyWeChat\Factory;

class Activity extends BaseController
{
    public $official = null;

    protected function initialize()
    {
        $config = [
            'app_id' => 'wx593405606cc12cb5',
            'secret' => '08fd589a8314cf897cf919c9b72880f5',
            // ...
            'oauth'  => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => "/web/oauthBack2",
            ],
            // ..
        ];

        $this->official = Factory::officialAccount($config);
    }

    public function oauthBack()
    {
        try {

            $code = $this->request->get('code');
            $user = $this->official->oauth->userFromCode($code);
            $user = $user->getRaw();

            $flag = true;
            if (!isset($user['unionid'])) {
                $flag = false;
            }
            $unionid = $user['unionid'];
            /**
             * 处理用户信息
             */
            $re = OfficialAccountModel::where('unionid', $unionid)->find();
            if (!$re) {
                OfficialAccountModel::create([
                    'unionid' => $unionid,
                    'openid'  => $user['openid'],
                ]);
            }

            $targetUrl = "/h5/pages/index/join?flag={$flag}";
            header('Location:' . $targetUrl); //
        } catch (\Exception $e) {
            exit($e->getMessage());
        }
    }

    public function oauth()
    {
        $oauth = $this->official->oauth;
        $redirectUrl = $oauth->redirect();
        header("Location: {$redirectUrl}");
        exit;
    }
}